
package com.neo.tiny.admin.service.msg.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neo.tiny.admin.entity.msg.SysMsgNotifyTemplateDO;
import com.neo.tiny.admin.mapper.msg.SysMsgNotifyTemplateMapper;
import com.neo.tiny.admin.service.msg.SysMsgNotifyTemplateService;
import com.neo.tiny.admin.vo.msg.SysMsgNotifyTemplateCreateReqVO;
import com.neo.tiny.admin.vo.msg.SysMsgNotifyTemplateUpdateReqVO;
import com.neo.tiny.common.exception.WebApiException;
import com.neo.tiny.query.LambdaQueryWrapperBase;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @Description: 站内信模板
 * @Author: yqz
 * @CreateDate: 2023-02-11 14:13:15
 */
@Service
public class SysMsgNotifyTemplateServiceImpl extends ServiceImpl<SysMsgNotifyTemplateMapper, SysMsgNotifyTemplateDO> implements SysMsgNotifyTemplateService {

    /**
     * 正则表达式，匹配 {} 中的变量
     */
    private static final Pattern PATTERN_PARAMS = Pattern.compile("\\{(.*?)}");


    @Override
    public Long createTemplate(SysMsgNotifyTemplateCreateReqVO req) {

        checkTemplateCode(null, req.getTemplateCode());
        SysMsgNotifyTemplateDO sysMsgNotifyTemplate = BeanUtil.copyProperties(req, SysMsgNotifyTemplateDO.class);

        List<String> templateParams = ReUtil.findAllGroup1(PATTERN_PARAMS, req.getTemplateContent());

        sysMsgNotifyTemplate.setTemplateParams(templateParams);
        this.save(sysMsgNotifyTemplate);

        return sysMsgNotifyTemplate.getId();
    }

    @Override
    public Boolean updateTemplate(SysMsgNotifyTemplateUpdateReqVO req) {
        checkTemplateCode(req.getId(), req.getTemplateCode());

        SysMsgNotifyTemplateDO template = BeanUtil.copyProperties(req, SysMsgNotifyTemplateDO.class);
        List<String> templateParams = ReUtil.findAllGroup1(PATTERN_PARAMS, req.getTemplateContent());
        template.setTemplateParams(templateParams);
        return this.updateById(template);
    }

    @Override
    public Boolean delTemplate(Long templateId) {


        return this.removeById(templateId);
    }

    private void checkTemplateCode(Long templateId, String templateCode) {
        SysMsgNotifyTemplateDO one = this.getOne(new LambdaQueryWrapperBase<SysMsgNotifyTemplateDO>()
                .eq(SysMsgNotifyTemplateDO::getTemplateCode, templateCode));

        if (BeanUtil.isEmpty(one)) {
            return;
        }
        // 如果id不为空，code能查询到数据，说明是更新操作，如果更新的id不相同，则说明已存在
        if (!one.getId().equals(templateId)) {
            throw new WebApiException("该模板已存在");
        }
    }

}
